﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Eb.MessageBox;
using Eb.StockManagement;
public partial class Modules_StockManagement_IssueForOthers : System.Web.UI.UserControl
{
    StockManagement stckMgmt=new StockManagement();
    static double grdTotalGeneral = 0;
    Purchase.Purchase purchase = new Purchase.Purchase();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            txtFrom.Text = DateReturn(DateTime.Now.ToString("MM-dd-yyyy"));
            txtTo.Text = DateReturn(DateTime.Now.ToString("MM-dd-yyyy"));
            lblViewDate.Text = DateTime.Now.ToShortDateString();
            GetUsers();
            SetInitialRow();
            PopulateDirection();
        }
    }

    protected void PopulateDirection()
    {
       DataSet ds= stckMgmt.GetDirection();
       ddlDirection.DataSource = ds;
       ddlDirection.DataTextField = "DirectionName";
       ddlDirection.DataValueField = "DirectionId";
       ddlDirection.DataBind();
       ddlDirection.Items.Insert(0, "Select");
        //}
    }
    protected void txtRequiredQty_TextChanged(object sender, EventArgs e)
    {
        htmlHidden.Value = gvItemDetails.Rows.Count.ToString();

      //  FindTotalAmountWithGeneralPurchase();
    }
 
    protected void FindTotalAmountWithGeneralPurchase()
    {
        double amt = 0;
        foreach (GridViewRow gvr in gvItemDetails.Rows)
        {
            TextBox tbQty = (TextBox)gvr.Cells[4].FindControl("txtRequiredQty");
            TextBox price = (TextBox)gvr.Cells[3].FindControl("txtUnitPrice");
            double price1 = Convert.ToDouble(price.Text);
            TextBox tbTotal = (TextBox)gvr.Cells[5].FindControl("txtTP");
            int totQty = Convert.ToInt16(tbQty.Text);


            tbTotal.Text = Convert.ToString(price1 * totQty);

            grdTotalGeneral = Convert.ToDouble(tbTotal.Text) + amt;
            amt = grdTotalGeneral;
            htmlHidden.Value = gvItemDetails.Rows.Count.ToString();

        }
        ((TextBox)gvItemDetails.FooterRow.FindControl("txtGrantTot")).Text = grdTotalGeneral.ToString("C2");
    }

    protected void lbRemove_Click(object sender, EventArgs e)
    {
        int grdCount = 0;
        LinkButton lb = (LinkButton)sender;
        GridViewRow gvRow = (GridViewRow)lb.NamingContainer;
        // int rowID = gvRow.RowIndex + 1;
        int rowID = gvRow.RowIndex;
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            if (dt.Rows.Count > 1)
            {
                if (gvRow.RowIndex < dt.Rows.Count - 1)
                {
                    //Remove the Selected Row data
                    dt.Rows.Remove(dt.Rows[rowID]);
                    grdCount = dt.Rows.Count - 1;
                }
            }
            //Store the current data in ViewState for future reference
            ViewState["CurrentTable"] = dt;
            //Re bind the GridView for the updated data
            gvItemDetails.DataSource = dt;
            gvItemDetails.DataBind();
            htmlHidden.Value = grdCount.ToString();
        }

        //Set Previous Data on Postbacks
        SetPreviousData();
    }
    void GetUsers()
    {
        //users coming under the selected group
        DataSet userDS = purchase.GetUsers();
        lbUserList.DataSource = userDS;
        lbUserList.DataTextField = "UserName";
        lbUserList.DataValueField = "UD_UserPersonalID";
        lbUserList.DataBind();
    }
    protected void lbUserList_PreRender(object sender, EventArgs e)
    {
        foreach (ListItem item in lbUserList.Items)
        {
            item.Attributes.Add("title","UserID:  "+ item.Value);
        }
    }
    protected void gvItemDetails_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //  FindTotalAmountWithGeneralPurchase();
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            LinkButton lb = (LinkButton)e.Row.FindControl("lbRemove");
            if (lb != null)
            {
                if (dt.Rows.Count > 1)
                {
                    if (e.Row.RowIndex == dt.Rows.Count - 1)
                    {
                        lb.Visible = false;
                    }
                }
                else
                {
                    lb.Visible = false;
                }
            }
        }

        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");

            e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");

        }
        if (e.Row.RowType == DataControlRowType.EmptyDataRow)
            e.Row.CssClass = "grid-view-header";
        if (e.Row.RowType == DataControlRowType.Header)
            e.Row.CssClass = "grid-view-header";

        //Add CSS class on normal row.
        if (e.Row.RowType == DataControlRowType.DataRow &&
                  e.Row.RowState == DataControlRowState.Normal)
            e.Row.CssClass = "grid-view-normal";

        //Add CSS class on alternate row.
        if (e.Row.RowType == DataControlRowType.DataRow &&
                  e.Row.RowState == DataControlRowState.Alternate)
            e.Row.CssClass = "grid-view-alternate";

        //if (e.Row.RowType == DataControlRowType.Footer)
        //{
        //    e.Row.Cells[2].Text = "Total Quantity:";
        //}
    }
    protected string DateReturn(string date)
    {
        string result = string.Empty;
        if (date.Contains("-"))
        {
            result = date.Replace("-", "/");
        }
        else
        {
            result = date;
        }
        return result;
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {

        TextBox tbQty = (TextBox)gvItemDetails.Rows[0].Cells[4].FindControl("txtProduct");
        if (tbQty.Text == null || tbQty.Text.Trim() == "")
        {
            MessageBox.Show("Please enter ProductDetails");
        }
        else
        {
            if (lbUserList.SelectedIndex < 0)
                MessageBox.Show("Please select a User");
            else
            {
                bool status;
                int direction = 0;
                if (ddlDirection.SelectedIndex > 0)
                    direction = Convert.ToInt16(ddlDirection.SelectedValue);
                int movedBy = 0;
                if (Session["UserId"] != null)
                    movedBy = Convert.ToInt16(Session["UserId"].ToString());
                int movedTo =Convert.ToInt16(lbUserList.SelectedValue);
                int uniqID = stckMgmt.InsertIssueForOthers(movedBy, movedTo, txtFrom.Text, txtFrom.Text,direction, txtRemarks.Text);
                if (uniqID > 0)
                {
                     foreach (GridViewRow gvr in gvItemDetails.Rows)
                     {
                         int qty=0;
                         TextBox tbQty1 = (TextBox)gvr.Cells[4].FindControl("txtRequiredQty");
                         TextBox txtProduct = (TextBox)gvr.Cells[3].FindControl("txtProduct");
                         TextBox specification = (TextBox)gvr.Cells[3].FindControl("txtSpecification");
                         if(tbQty.Text!="" || tbQty.Text!=null)
                         {
                             qty=Convert.ToInt16(tbQty1.Text.Trim());
                         }
                         status = stckMgmt.InsertIssueForOthers(uniqID,txtProduct.Text,qty,specification.Text);
                     }
                }
            }

            //int uniqID=stckMgmt.InsertIssueForOthers(
        }

    }
    protected void ButtonAdd_Click(object sender, EventArgs e)
    {
        AddNewRowToGrid();
    }
    private void SetInitialRow()
    {
        DataTable dt = new DataTable();
        DataRow dr = null;
        dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
        dt.Columns.Add(new DataColumn("Column1", typeof(string)));
        dt.Columns.Add(new DataColumn("Column2", typeof(string)));
        //dt.Columns.Add(new DataColumn("Column3", typeof(string)));
        dt.Columns.Add(new DataColumn("Column3", typeof(string)));
        //dt.Columns.Add(new DataColumn("Column4", typeof(string)));
        dr = dt.NewRow();
        dr["RowNumber"] = 1;
        dr["Column1"] = string.Empty;
        dr["Column2"] = string.Empty;
       // dr["Column3"] = string.Empty;
        dr["Column3"] = string.Empty;
      //  dr["Column4"] = string.Empty;
        dt.Rows.Add(dr);
        //Store the DataTable in ViewState
        ViewState["CurrentTable"] = dt;
        gvItemDetails.DataSource = dt;
        gvItemDetails.DataBind();
        htmlHidden.Value = "0";
    }
    private void AddNewRowToGrid()
    {
        int rowIndex = 0;

        if (ViewState["CurrentTable"] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
            DataRow drCurrentRow = null;
            if (dtCurrentTable.Rows.Count > 0)
            {
                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {
                    //extract the TextBox values
                    // DropDownList box1 = (DropDownList)gvItemDetails.Rows[rowIndex].Cells[1].FindControl("ddlItemName");
                    TextBox box1 = (TextBox)gvItemDetails.Rows[rowIndex].Cells[2].FindControl("txtProduct");
                    TextBox box2 = (TextBox)gvItemDetails.Rows[rowIndex].Cells[2].FindControl("txtRequiredQty");
                    TextBox box3 = (TextBox)gvItemDetails.Rows[rowIndex].Cells[3].FindControl("txtSpecification");
                    //TextBox box4 = (TextBox)gvItemDetails.Rows[rowIndex].Cells[3].FindControl("txtTP");
                   // TextBox box5 = (TextBox)gvItemDetails.Rows[rowIndex].Cells[3].FindControl("txtSpecification");



                    drCurrentRow = dtCurrentTable.NewRow();
                    drCurrentRow["RowNumber"] = i + 1;

                    if (box1.Text.Trim() != "" && box2.Text.Trim() != "")
                    {
                        lblErrMessage.Visible = false;
                        lblErrMessage.Text = "";
                        dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
                        dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
                        dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;
                        //dtCurrentTable.Rows[i - 1]["Column4"] = box4.Text;
                      //  dtCurrentTable.Rows[i - 1]["Column5"] = box5.Text;
                        //  itemIndex = Convert.ToInt16(box1.SelectedValue);
                        rowIndex++;
                    }
                    else
                    {
                        lblErrMessage.Visible = true;
                        lblErrMessage.Text = "Please Fill all Fields";
                        return;
                    }
                }
                dtCurrentTable.Rows.Add(drCurrentRow);
                ViewState["CurrentTable"] = dtCurrentTable;

                gvItemDetails.DataSource = dtCurrentTable;
                gvItemDetails.DataBind();
                htmlHidden.Value = gvItemDetails.Rows.Count.ToString();

            }
        }
        else
        {
            Response.Write("ViewState is null");
        }

        //Set Previous Data on Postbacks
        SetPreviousData();
    }

    private void SetPreviousData()
    {
        int rowIndex = 0;
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            if (dt.Rows.Count > 0)
            {
                // GetMaterials();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    // DropDownList box1 = (DropDownList)gvItemDetails.Rows[rowIndex].Cells[1].FindControl("ddlItemName");
                    TextBox box1 = (TextBox)gvItemDetails.Rows[rowIndex].Cells[1].FindControl("txtProduct");
                    TextBox box2 = (TextBox)gvItemDetails.Rows[rowIndex].Cells[4].FindControl("txtRequiredQty");
                    //TextBox box3 = (TextBox)gvItemDetails.Rows[rowIndex].Cells[3].FindControl("txtUnitPrice");
                    TextBox box3 = (TextBox)gvItemDetails.Rows[rowIndex].Cells[3].FindControl("txtSpecification");
                   // TextBox box5 = (TextBox)gvItemDetails.Rows[rowIndex].Cells[2].FindControl("txtSpecification");
                   // TextBox box6 = (TextBox)gvItemDetails.FooterRow.FindControl("txtGrantTot");
                    if (i < dt.Rows.Count - 1)
                    {
                        //   box1.ClearSelection();
                        //   box1.Items.FindByText(dt.Rows[i]["Column1"].ToString()).Selected = true;
                        box1.Text = dt.Rows[i]["Column1"].ToString();
                        box2.Text = dt.Rows[i]["Column2"].ToString();
                       // box3.Text = dt.Rows[i]["Column3"].ToString();
                        box3.Text = dt.Rows[i]["Column3"].ToString();
                      //  box5.Text = dt.Rows[i]["Column5"].ToString();
                      //  box6.Text = grdTotalGeneral.ToString("C2");
                    }


                    rowIndex++;
                }
            }
        }
    }

}
